import util from '../../utils/util';
const qcloud = require('../../vendor/sdk/index');
const config = require('../../config');
const app = getApp();
var timer = null;
Page({
  data: {
    platform: app.globalData.platform,
    fileHost: app.globalData.imageUrl,
    navH: app.globalData.navHeight,
    theme: config.theme,
    startPoint: [0, 0], // 初始化touchstart坐标
    emojis: util.emoji,
    emojiTotalNum: Math.ceil(util.emoji.length / 20),
    messages: [],
    images: {
      talkingImageList: [], //预览用户头像图片列表
      userHeadImageList: [] //预览聊天框图片列表
    },
    systemMessageUuid: 0, //用于生成系统提示消息: 主要包括两个: 1.滑到顶部提示没有更多数据; 2.第一次进入在底部添加可以开始聊天提示
    readedMessage: [],
    inputContent: '',
    aiteUserList: [],
    lastMessageId: '',
    noticeMessageId: '',
    programId: '',
    program: {},
    isSubscribe: '',
    currentUserInfo: app.globalData.userInfo,
    showDesc: false,
    onlineCount: 0,
    totalCount: 0,
    modalVisible: false,
    loading: true,
    userToolsTipLeft: '10px',
    userToolsTipTop: '10px',
    userToolsTip: false, //普通用户消息操作提示
    adminToolsTip: false, //管理员消息操作提示
    inputToolsTip: false, //输入框长按操作提示
    actionMessage: null, //操作消息对象
    msgNoMore: false,
    msgPageNum: 1,
    msgPageSize: 20,
    height: wx.getSystemInfoSync().windowHeight,
    scrollTop: 0,
    loadingMore: false,
    toolPanelValue: '',
    showText: '按住说话',
    recorderManager: null,
    backgroundAudioManager: null,
    voiceMaxSeconds: 60,
    voiceSeconds: 0,
    voiceSencondsTimer: null,
    deleteVoice: false,
    sendVoiceToast: 0,
    sourceType: null,
    leaveProgram: false,
    scrollPosition: 'lower', //默认聊天框处于底部: lower-底部位置; middle-中间位置
    hideModal: true, //底部模态框的状态  true-隐藏  false-显示
    animationData: {}, //底部模态框动画
    bottomDialogTipText: '',
    operateFlag: {
      // 主要用户判断是否通过下面三种情况出发onHide事件
      previewImg: false, // 预览图片：包括预览聊天框图片和预览用户头像图片onHide
      callCamera: false, // 调用相机触发onHide事件
      callAlbum: false // 调用相册触发onHide事件
    },
    hideShareModal: true, //分享按钮模态框状态,
    option: null,
    webViewUrl: null,
    inputTextTip: '说点什么...',
    textTipTimer: null
  },
  onLoad(option) {
    this.setData({
      height: wx.getSystemInfoSync().windowHeight,
      currentUserInfo: app.globalData.userInfo,
      option: option,
    });
    let type = option.type;
    let sourceType = null;
    let programId = null;
    if (!type && option.scene) {
      sourceType = 'qrcode';
      programId = option.scene;
    } else if (type == 'forward') {
      sourceType = 'forward';
      programId = option.programId;
    } else {
      sourceType = 'program';
      programId = option.programId;
    }
    this.setData({
      sourceType,
      programId,
      noticeMessageId: option.messageId ? option.messageId : this.data.noticeMessageId,
      scrollLeft: option.scrollLeft ? option.scrollLeft : 0,
    }, () => {
      this.getProgramById(programId);
      this.init();
      this.voiceReadTimer();
    });
    this.inputTextTipTimer();
  },
  onPageScroll(e) {
  },
  onReady() {
    let page = `../chat/chat?programId=${this.data.programId}`;
    if (app.globalData.userInfo && app.globalData.userInfo.role != -1) {
      this.updateLastVisitPage(page);
    }
  },
  onShow() {
    // 由于第一次进入互动页 this.tunnel == null, 通信信道链接会在onLoad里面进行,这里onShow主要用于在锁屏以后等断线的时候进行信道断开以后的链接
    if (this.tunnel != null && (this.tunnel.isClosed() || !this.tunnel.isActive())) {
      console.log('onShow 进入重连');
      if (this.tunnel.close()) {
        console.log('onShow 关闭以后再次重新链接');
        this.enter();
      }
    }
    // 将 operateFlag 重置为初始值
    this.setData({
      operateFlag: { previewImg: false, callCamera: false, callAlbum: false }
    });
  },
  onHide() {
    // 取出 operateFlag 判断此次触发onHide是否是：预览聊天图片/预览头像图片/调用相机/调用相册
    let operateFlag = this.data.operateFlag;
    if (!(operateFlag.previewImg || operateFlag.callCamera || operateFlag.callAlbum)) {
      this.stopCurrentPlayVoiceMessage();
      util.syncReadedVoiceMessage();
    }
  },
  onUnload() {
    this.stopCurrentPlayVoiceMessage();
    util.syncReadedVoiceMessage();
    if (app.globalData.userInfo && app.globalData.userInfo.role != -1) {
      this.updateLastVisitPage(null);
    }
    this.quit();
  },
  onNavBack() {
    let previousChatRoomProgram = JSON.stringify(this.data.program);
    clearInterval(this.data.textTipTimer);
    wx.redirectTo({
      url: `/pages/index/index?previousChatRoomProgram=${previousChatRoomProgram}&scrollLeft=${this.data.scrollLeft}`
    });
  },
  init() {
    let self = this;
    // 初始化录音对象 recorderManager
    if (!this.data.recorderManager) {
      let recorderManager = wx.getRecorderManager();
      this.setData({
        recorderManager
      });
      // 监听录音结束事件
      recorderManager.onStop(function (res) {
        // 判断该录音是否被删除
        if (self.data.deleteVoice) {
          self.setData({
            deleteVoice: false
          });
          return;
        }
        // 判断录音时长
        if (self.data.voiceSeconds < 1) {
          wx.showToast({
            title: '录音时间太短',
            icon: 'none',
            duration: 2000
          });
          self.setData({
            voiceSeconds: 0
          });
          return;
        }
        wx.showLoading({
          title: '发送中...',
          icon: 'loading',
          duration: 60000
        });
        clearInterval(self.data.voiceSencondsTimer);
        self.setData({
          voiceSencondsTimer: null
        });
        wx.uploadFile({
          url: config.service.uploadFileUrl,
          filePath: res.tempFilePath,
          name: 'file',
          formData: {},
          success: function (res) {
            wx.hideLoading();
            let response = JSON.parse(res.data);
            if (response.success) {
              let voiceUrl = response.data.path;
              self.sendMessage({
                msgType: 'voice',
                content: voiceUrl,
                read: 0
              });
            }
          }
        });
      });
    }

    if (!this.data.backgroundAudioManager) {
      let backgroundAudioManager = wx.getBackgroundAudioManager();
      // 监听方法
      backgroundAudioManager.onPlay(() => {
        console.log('监听背景音频播放事件');
      });
      backgroundAudioManager.onError(e => {
        console.log('监听背景音频播放错误事件', e);
        console.log('监听到背景音频播放错误事件以后将正在播放的语音条停止闪动');
        let messages = self.data.messages;
        let voiceArr =
          messages && messages.filter(item => item.msgType === 'voice');
        voiceArr.forEach(msg => {
          if (msg.voicePlay === true) {
            msg.voicePlay = false;
          }
        });
        self.setData({
          messages
        });
      });
      backgroundAudioManager.onPause(() => {
        console.log('监听背景音频暂停事件');
      });
      backgroundAudioManager.onEnded(() => {
        console.log('监听背景音频自然播放结束事件');
        let messages = self.data.messages;
        let voiceArr =
          messages && messages.filter(item => item.msgType === 'voice');
        let playVoiceMessage = null;
        voiceArr.forEach(msg => {
          if (msg.voicePlay === true) {
            msg.voicePlay = false;
            playVoiceMessage = msg;
          }
        });
        // 如果当前播放的语音是别人的语音【该条语音是第一次播放】 && 下一条别人的语音是未读的那么继续播放下一条别人语音消息
        let firstRead = playVoiceMessage.firstRead && playVoiceMessage.firstRead;
        if (firstRead && playVoiceMessage.userId !== self.data.currentUserInfo.id) {
          let otherVoiceArr = voiceArr && voiceArr.filter(item => item.userId !== self.data.currentUserInfo.id);
          let nextOtherVoiceMessage = null;
          otherVoiceArr && otherVoiceArr.forEach((item, index) => {
            if (item.uuid === playVoiceMessage.uuid) {
              nextOtherVoiceMessage = index + 1 > otherVoiceArr.length ? null : otherVoiceArr[index + 1];
            }
          });
          if (nextOtherVoiceMessage && nextOtherVoiceMessage.read == 0) {
            this.commonAudioPlayFun(nextOtherVoiceMessage);
            nextOtherVoiceMessage.voicePlay = true;
            nextOtherVoiceMessage.read = 1;
            nextOtherVoiceMessage.firstRead = true;
          } else {
            // 解除语音播放屏幕常亮
            wx.setKeepScreenOn({
              keepScreenOn: false,
              success: () => {
                console.log('自然播放完毕解除语音播放屏幕常亮');
              }
            });
          }
        }
        self.setData({
          messages
        });
      });
      backgroundAudioManager.onStop(e => {
        console.log('监听背景音频停止事件', e);
      });
      this.backgroundAudioManager = backgroundAudioManager;
      this.setData({
        backgroundAudioManager
      });
    }
  },
  updateLastVisitPage(page) {
    if (page && this.data.currentUserInfo && this.data.currentUserInfo.id) {
      console.log('updateLastVisitPage-fun 更新最后浏览页', page, this.data.currentUserInfo);
      qcloud.request({
        url: config.service.updateLastVisitPageUrl,
        data: {
          page: page,
          userId: this.data.currentUserInfo.id
        },
        success: res => {
          console.log('保存浏览页面成功');
        }
      });
    }
  },
  quit() {
    // 退出聊天室
    if (this.tunnel) {
      console.log('退出聊天室', this.tunnel);
      try {
        this.tunnel.close();
      } catch (e) {
        console.log('退出聊天室error:', e);
      }
    }
  },
  voiceReadTimer() {
    setInterval(() => {
      util.syncReadedVoiceMessage();
    }, 60 * 1000);
  },
  inputTextTipTimer() {
    let self = this;
    let maxNum = 20;//循环 10 次
    let num = 0;
    var timer = setInterval(() => {
      num++;
      console.log(num);
      let targetTip = '说点什么...';
      if (self.data.inputTextTip === '说点什么...') {
        targetTip = '粘贴公众号文章链接即可发送';
      }
      self.setData({
        inputTextTip: targetTip,
        textTipTimer: timer,
      });
      if (num >= maxNum) {
        clearInterval(timer);
        self.setData({
          inputTextTip: '说点什么...',
          textTipTimer: null
        });
      }
    }, 5 * 1000);
  },
  getProgramById(id) {
    // 获取互动信息
    let self = this;
    qcloud.request({
      url: config.service.getProgramInfoUrl,
      data: {
        id: id
      },
      success: res => {
        console.log('getProgramById-res', res);
        let program = res.data.data;
        if (!program) {
          wx.redirectTo({
            url: '/pages/index/index'
          })
          // wx.showToast({
          //   title: '互动不存在或已删除',
          //   icon: 'none'
          // });
        } else {
          self.setData({
            loading: false,
            programId: id,
            program: program
          }, () => {
            this.enter();
          });
        }
      }
    });
  },
  enter() {
    // 如果登录过，会记录当前用户在 this.me 上
    if (!this.me) {
      console.log('enter-getUserInfo');
      app.getUserInfo().then(currentUserInfo => {
        console.log('eneter-userInfo', currentUserInfo);
        let isSubscribe = currentUserInfo.role !== -1 && currentUserInfo.subscribe && currentUserInfo.subscribe.includes(this.data.programId);
        this.me = currentUserInfo;
        this.setData({
          currentUserInfo: currentUserInfo,
          isSubscribe: isSubscribe ? true : false
        }, () => {
          // 进入聊天室的时候没有用户信息在此处获取到用户信息以后进行最后浏览聊天室的信息存储
          let page = `../chat/chat?programId=${this.data.programId}`;
          if (app.globalData.userInfo && app.globalData.userInfo.role != -1) {
            this.updateLastVisitPage(page);
          }
          this.connect();
        });
      });
    } else {
      console.log('enter-connect');
      this.connect();
    }
  },
  connectSuccessQueryNewData() {
    console.log('连接信道成功查询最新聊天记录数据');
    let self = this;
    console.log('连接成功重置相关数据状态');
    // 连接成功重置相关数据状态
    this.setData({
      messages: [],
      msgPageNum: 1,
      scrollPosition: 'lower',
      lastMessageId: ''
    });

    this.getData(() => {
      console.log('连接成功拉取最新数据-then 回调');
      this.setData({
        scrollPosition: 'lower'
      }, () => {
        this.pushMessage(this.createSystemMessage('可以开始聊天了'));
      });
    });
  },
  connect() {
    // 连接到聊天室信道服务 - 避免重复创建信道
    if (this.tunnel && this.tunnel.isActive()) {
      console.log(`${new Date()}: 信道服务存在`);
      return;
    }

    if (!(this.data.programId && this.data.currentUserInfo.account)) {
      return;
    }
    // 创建信道
    let url = `${config.service.tunnelUrl}/${this.data.programId}/${this.data.currentUserInfo.account}?env=${config.env}`;
    console.log('创建信道url', url);
    var tunnel = (this.tunnel = new qcloud.Tunnel(url));

    // 连接成功后，去掉「正在加入群聊」的系统提示
    let self = this;
    tunnel.on('connect', () => {
      console.log(`connect-连接成功`);
      self.connectSuccessQueryNewData();
    });

    // 监听信道消息类型-聊天室有人加入或退出，反馈到 UI 上
    tunnel.on('people', people => {
      const { totalCount, onlineCount } = people;
      this.setData({
        totalCount,
        onlineCount
      });
    });

    // 监听操作类型 - 有人说话，创建一条消息
    tunnel.on('message', message => {
      this.convertMessage(message);
      if (message.msgType === 'image') {
        let talkingImageList = this.data.images.talkingImageList;
        talkingImageList.push(message.content);
        this.setData({
          images: Object.assign({}, this.data.images, { talkingImageList })
        });
      } else if (message && message.msgType === 'link') {
        // 处理 link 消息类型
        message.content = message.content;
      }
      this.pushMessage(message);
    });

    // 解除禁言
    tunnel.on('removeBlackList', message => {
      console.log('解除禁言', message);
      let currentUser = self.data.currentUserInfo;
      if (message && currentUser && message.userId === currentUser.id) {
        currentUser.isForbidSpeak = 'N'; // 解除禁言
      }
      self.setData({ currentUserInfo: currentUser }, () => {
        self.pushMessage(this.createSystemMessage(`禁言已解除`));
      });
    });

    // 禁言
    tunnel.on('addBlackList', message => {
      console.log('禁言', message);
      // 清理掉当前state中的被禁言用户的消息记录
      let messages = self.data.messages;
      if (messages != null) {
        messages = messages.filter(item => item.userId != message.userId);
      }
      let currentUser = self.data.currentUserInfo;
      if (message && currentUser && message.userId === currentUser.id) {
        currentUser.isForbidSpeak = 'Y'; // 禁言
      }
      self.setData({
        messages,
        currentUserInfo: currentUser
      }, () => {
        let userName = message.userName === this.data.currentUserInfo.name ? '你已' : `"${message.userName}"`;
        self.pushMessage(this.createSystemMessage(`${userName}被禁言了`));
      });
    });

    // 撤回
    tunnel.on('withdraw', message => {
      let messages = [...this.data.messages];
      let index = messages.findIndex(v => v.id == `history_${message.id}`);

      let withdrawMessage = messages[index];
      withdrawMessage.status = '2';
      withdrawMessage.withdrawContent =
        message.userName === this.data.currentUserInfo.name
          ? '你撤回了一条消息'
          : `"${message.userName}" 撤回了一条消息`;
      this.setData({ messages });
    });

    // 重连提醒
    tunnel.on('reconnecting', () => {
      console.log(`${new Date()}: 已断线，正在重连, 清除数据`);
    });

    tunnel.on('reconnect', () => {
      console.log(`${new Date()}: 重连成功-调用连接成功方法获取最新数据`);
      // 重连成功后拉去一次最新数据
      self.connectSuccessQueryNewData();
    });

    // 打开信道
    tunnel.open();
  },
  createSystemMessage(content) {
    // 生成聊天室的系统消息
    return {
      id: `system-message-${++this.data.systemMessageUuid}`,
      msgType: 'system',
      content
    };
  },
  onShareAppMessage(options) {
    console.log('分享');
    let self = this;
    let shareObj = {
      title: `${this.data.theme.wechatName} | ${this.data.program.name} 正在互动...`,
      path: '/pages/chat/chat?type=forward&programId=' + this.data.programId,
      success: function (res) {
        console.log('分享-success', res);
        // 转发成功之后的回调
        if (options.from == 'button') {
          console.log('转发按钮分享聊天框');
        }
      },
    };
    console.log('hideShareModal');
    self.hideShareModal();
    // 分享
    return shareObj;
  },
  getUserInfo(e) {
    let self = this;
    console.log('getUserInfo-function', e);
    // 授权成功
    wx.login({
      success: res => {
        let rawData = e.detail.rawData;
        if (rawData) {
          let userInfo = JSON.parse(rawData);
          let wxUserInfo = {
            code: res.code,
            ...userInfo
          };
          // 设置全局变量并返回上一页
          app.globalData.wxUserInfo = wxUserInfo;
          app.loginIteraction(wxUserInfo, () => {
            // 刷新当前页
            self.onLoad(self.data.option);
            if (e.currentTarget.dataset.follow && e.currentTarget.dataset.follow === 'follow-btn') {
              self.subscribeProgram();
            }
          });
        }
      }
    });
  },
  goPoster() {
    if (!this.data.program.appletCodeUuid) {
      wx.showToast({
        title: '尚未发布,发布以后方可进行分享',
        icon: 'none',
        image: '',
        duration: 1500,
        mask: false
      });
      this.hideShareModal();
      return;
    }
    let program = JSON.stringify({
      id: this.data.program.id,
      programName: this.data.program.name,
      programLogoUuid: this.data.program.logo,
      userLogoUuid: this.data.currentUserInfo.photo,
      appletCodeUuid: this.data.program.appletCodeUuid
    });
    console.log('分享相关数据', program);
    console.log('goPoster');
    this.hideShareModal();
    wx.navigateTo({
      url: `../poster/poster?program=${program}`
    });
  },
  showProgramDescription() {
    // 展示互动简介
    this.setData({
      showDesc: !this.data.showDesc
    });
  },
  copyMsg() {
    // 按住复制消息
    this.hideToolsTip();
    let msg = this.data.actionMessage;
    wx.setClipboardData({
      data: msg.content
    });
  },
  openLink(e) {
    let actionMessage = e.currentTarget.dataset.message;
    console.log('webview-url', actionMessage.content.targetUrl);
    let webViewUrl = actionMessage.content.targetUrl;
    wx.navigateTo({
      url: `/pages/webview/webview?webViewUrl=${webViewUrl}`
    });
  },
  showUserToolsTip(e) {
    // 展示消息操作栏
    let actionMessage = e.currentTarget.dataset.message;
    // 计算是否超过 2 分钟
    let nowNum = new Date().getTime();
    let createNum = new Date(actionMessage.createTime.replace(/-/g, '/')).getTime();
    let diffNum = nowNum - createNum;
    actionMessage.overTime = diffNum > 120 * 1000 ? true : false;
    console.log('showUserToolsTip, nowNum, createNum, diffNum', nowNum, createNum, diffNum);
    console.log('actionMessage.overTime ', actionMessage);

    let offsetLeft = e.detail.x;
    let offsetTop = e.detail.y;
    offsetTop = offsetTop - 130 + 'px';
    if (actionMessage.userId === this.data.currentUserInfo.id) {
      // 自己消息-文本类消息-复制和撤销; 图片、语音类消息-撤回
      offsetLeft = offsetLeft - 60 + 'px';
      this.setData({
        userToolsTip: true,
        userToolsTipLeft: offsetLeft,
        userToolsTipTop: offsetTop,
        actionMessage
      });
    } else {
      // 别人消息-文本类消息-复制
      offsetLeft = offsetLeft - 30 + 'px';
      this.setData({
        adminToolsTip: true,
        userToolsTipLeft: offsetLeft,
        userToolsTipTop: offsetTop,
        actionMessage
      });
    }
  },
  showInputToolsTip(e) {
    // 展示消息操作栏
    let offsetLeft = e.detail.x;
    let offsetTop = e.detail.y;
    offsetTop = offsetTop - 130 + 'px';
    offsetLeft = offsetLeft - 60 + 'px';
    this.setData({
      inputToolsTip: true,
      userToolsTipLeft: offsetLeft,
      userToolsTipTop: offsetTop,
    });
  },
  hideToolsTip() {
    // 隐藏消息操作栏
    this.setData({
      userToolsTip: false,
      adminToolsTip: false,
      inputToolsTip: false,
    });
  },
  pasteMsg(e) {
    let self = this;
    wx.getClipboardData({
      success: function (res) {
        console.log("粘贴 = ", res.data) // data
        self.setData({
          inputContent: res.data
        });
        self.hideToolsTip();
      }
    })
  },
  countFans() {
    //统计粉丝数量
    qcloud.request({
      url: config.service.countFansUrl,
      data: {
        userId: this.data.currentUserInfo.id
      },
      success: res => {
        console.log('countfans', res);
      }
    });
  },
  commonAudioPlayFun(voiceMessage) {
    if (this.backgroundAudioManager) {
      let self = this;
      let backgroundAudioManager = this.backgroundAudioManager;
      wx.downloadFile({
        url: self.data.fileHost + voiceMessage.content,
        success(res) {
          console.log('下载语音消息 voice-file-res', res);
          if (res.statusCode === 200) {
            console.log('语音消息下载成功,设置背景语音播放地址');
            backgroundAudioManager.title = '互动语音';
            backgroundAudioManager.src = res.tempFilePath;
            self.setData({
              currPlaySrc: res.tempFilePath
            });
          }
        }
      });
    }
    let readedMessage = this.data.readedMessage;
    if (voiceMessage.read == 0) {
      readedMessage.push(voiceMessage.uuid);
    }
    this.updateReadedVoiceMessageRecord(readedMessage);
  },
  clearReadedVoiceMessageRecord() {
    // 清空readMessage
    this.setData({
      readedMessage: []
    });
    wx.removeStorageSync('readedVoiceMessage');
  },
  updateReadedVoiceMessageRecord(readedVoiceMessage) {
    // 更新readMessage
    this.setData({
      readedMessage: readedVoiceMessage
    });
    wx.setStorageSync('readedVoiceMessage', {
      programId: this.data.programId,
      userId: this.data.currentUserInfo.id,
      uuid: readedVoiceMessage.join(',')
    });
  },
  subscribeProgram() {
    if (this.data.isSubscribe) return;
    // 订阅当前互动
    qcloud.request({
      url: config.service.subscribeProgramUrl,
      data: {
        userId: this.data.currentUserInfo.id,
        programId: this.data.programId
      },
      success: res => {
        wx.showToast({
          title: '关注成功',
          icon: 'success',
          duration: 2000
        });
        app.refreshUserInfo();
        this.setData({
          isSubscribe: true
        });
      }
    });
  },
  atSomeone(e) {
    // @某人
    let message = e.currentTarget.dataset.message || this.data.actionMessage;
    if (message.userId === this.data.currentUserInfo.id) {
      return;
    }

    // 是否已经包含需要@的人
    let aiteUserList = this.data.aiteUserList;
    let newAiteUserList = aiteUserList.filter(item => item === message.userId);
    if (newAiteUserList.length == 0) {
      aiteUserList.push(message.userId);
    }

    this.setData({
      inputContent: this.data.inputContent + `@${message.userName} `,
      modalVisible: false
    });
  },
  showPersonalPageModal(e) {
    // 展示个人信息
    let actionMessage = e.currentTarget.dataset.message;
    let userHeadImageList = [];
    actionMessage.photo && userHeadImageList.push(actionMessage.photo);
    actionMessage.photo1 && userHeadImageList.push(actionMessage.photo1);
    actionMessage.photo2 && userHeadImageList.push(actionMessage.photo2);
    this.setData({
      modalVisible: true,
      actionMessage,
      images: Object.assign({}, this.data.images, { userHeadImageList })
    });
    this.countFans();
  },
  hidePersonalPageModal() {
    // 隐藏个人信息
    this.setData({
      modalVisible: false
    });
  },
  updateMessages(newMsg, updater) {
    //  通用更新当前消息集合的方法
    let messages = this.data.messages;

    // 规避重复添加出现两条消息
    let arr = messages.filter(item => item.id === newMsg.id);
    if (arr && arr.length == 0) {
      console.log('规避重复添加出现两条消息触发', newMsg);
      return;
    }

    updater(messages);
    console.log('上一步滚动消息id', this.data.lastMessageId);
    let lastMessage = messages[messages.length - 1];
    console.log('现在需要滚动消息id', lastMessage.id);

    // 当前处于消息底部时有新消息进入自动刷新位置
    console.log('当前是否是处于消息底部：', this.data.scrollPosition);
    console.log('是否是自己的消息：', lastMessage.userId, this.data.currentUserInfo.id);
    if (this.data.scrollPosition === 'lower' || lastMessage.userId === this.data.currentUserInfo.id) {
      // 需要先更新 messagess 数据后再设置滚动位置，否则不能生效
      let lastMessageId = messages.length ? lastMessage.id : '';
      console.log('updateMessages-lasteMessageId', lastMessageId);
      console.log('scrollPosition', this.data.scrollPosition);
      this.setData({
        lastMessageId,
        messages
      });
    } else {
      this.setData({
        messages
      });
    }

    // 处理@跳转
    if (this.data.noticeMessageId) {
      console.log('---->@跳转滚动');
      let lasteMessageId = 'history_'+this.data.noticeMessageId;
      this.setData({
        lastMessageId: lasteMessageId
      }, () => {
        console.log('---->@跳转滚动以后，清空noticeMessageId');
        this.setData({
          noticeMessageId: null
        });
      });
    }
  },
  pushMessage(message) {
    console.log('追加新消息', message);
    // 追加一条消息
    this.updateMessages(message, messages => {
      // 规避重复添加出现两条消息
      let arr = messages.filter(item => item.id === message.id);
      if (arr && arr.length == 0) {
        messages.push(message);
      }
    });
  },
  unshiftMessage(message) {
    // 从头部插入
    this.updateMessages(message, messages => messages.unshift(message));
  },
  amendMessage(message) {
    // 替换上一条消息
    this.updateMessages(message, messages => messages.splice(-1, 1, message));
  },
  popMessage() {
    // 删除上一条消息
    this.updateMessages(message, messages => messages.pop());
  },
  changeInputContent(e) {
    // 用户输入的内容改变之后
    this.setData({
      inputContent: e.detail.value
    });
  },
  deleteInputContent(e) {
    let inputContent = this.data.inputContent;
    if (!inputContent) {
      return;
    }
    // 判断是否是表情
    let char = inputContent.substring(
      inputContent.length - 2,
      inputContent.length
    );
    let flag = false;
    util.emoji.forEach(it => {
      if (it.char === char) {
        flag = true;
      }
    });
    inputContent = flag
      ? inputContent.substring(0, inputContent.length - 2)
      : inputContent.substring(0, inputContent.length - 1);
    this.setData({
      inputContent
    });
  },
  sendMessage(e) {
    // 判断是否被禁言
    if (this.data.currentUserInfo && this.data.currentUserInfo.isForbidSpeak == 'Y') {
      this.pushMessage(this.createSystemMessage('你已被禁言了'));
      return;
    }
    console.log('发送消息：this.tunnel.isClosed()=', this.tunnel.isClosed());
    console.log('发送消息：this.tunnel.isActive()=', this.tunnel.isActive());
    if (this.tunnel.isClosed() || !this.tunnel.isActive()) {
      // this.pushMessage(createSystemMessage('您还没有加入群聊，正在加入...'));
      console.log('进入重连');
      if (this.tunnel.close()) {
        console.log('关闭以后再次重新链接');
        this.enter();
      }
    }

    // 默认为文本消息
    let msgType = 'text';
    let content = this.data.inputContent.trim();
    let detail = null;
    if (e.type && e.type === 'tap') {
      // 处理文本类消息
      if (e.currentTarget.dataset.fast && e.currentTarget.dataset.fast === 'fast') {
        // 快捷消息
        content = e.currentTarget.dataset.message;
      } else if (util.urlCheck(content)) {
        wx.showToast({
          title: '已发送',
          icon: 'success',
          duration: 2000
        });
        msgType = 'link';
      }
    } else if (e.type && e.type === 'confirm') {
      content = e.detail.value;
    } else {
      // 处理图片语音类消息
      msgType = e.msgType;
      content = e.content;
      detail = e.detail;
    }

    setTimeout(() => {
      let voiceSeconds = this.data.voiceSeconds;
      if (msgType === 'voice') {
        if (voiceSeconds == 0) {
          voiceSeconds = 1;
        } else if (voiceSeconds > 60) {
          voiceSeconds = 60;
        }
      }
      if (content && this.tunnel) {
        // 构造消息对象
        let messageContent = {
          content,
          aiteUserList: this.data.aiteUserList.join(','),
          msgType,
          voicePlay: false,
          programId: this.data.programId,
          userId: this.data.currentUserInfo.id,
          voiceSeconds,
          read: e.read,
          detail: detail
        };
        this.tunnel.emit(messageContent);
        let self = this;
        this.setData({
          inputContent: '',
          voiceSeconds: 0
        }, () => {
          console.log('发送消息以后清空消息是否成功，现在 inputContent 值', self.data.inputContent);
        });
      }
    });
  },
  previewImage: function (e) {
    // 预览图片
    this.setData({
      operateFlag: Object.assign({}, this.data.operateFlag, {
        previewImg: true
      })
    });
    wx.previewImage({
      current: e.target.dataset.src,
      urls:
        e.target.dataset.type === 'talking'
          ? this.data.images.talkingImageList
          : this.data.images.userHeadImageList
    });
  },
  chooseImage(e) {
    // 选择照片或拍照
    let self = this;
    let sourceType = e.currentTarget.dataset.type;
    if (sourceType === 'album') {
      this.setData({
        operateFlag: Object.assign({}, this.data.operateFlag, {
          callAlbum: true
        })
      });
    } else if (sourceType === 'camera') {
      this.setData({
        operateFlag: Object.assign({}, this.data.operateFlag, {
          callCamera: true
        })
      });
    }
    wx.chooseImage({
      count: 1, // 默认
      sizeType: ['original', 'compressed'],
      sourceType: [sourceType],
      success: function (res) {
        wx.showLoading({
          title: '发送中...'
        });
        let imageMessage = {};
        let tmpUrl = res.tempFilePaths && res.tempFilePaths[0];
        wx.getImageInfo({
          src: tmpUrl,
          success: function (infoRes) {
            imageMessage.detail = {
              height: infoRes.height,
              width: infoRes.width
            };
          }
        });

        wx.uploadFile({
          url: config.service.uploadFileUrl,
          filePath: tmpUrl,
          name: 'file',
          formData: {},
          success: function (res) {
            wx.hideLoading();
            let response = JSON.parse(res.data);
            if (response.success) {
              imageMessage.content = response.data.path;
              imageMessage.msgType = 'image';
              self.sendMessage(imageMessage);
            }
          }
        });
      }
    });
  },
  inputChange(e) {
    console.log('inputChange');
    if (this.data.textTipTimer != null) {
      clearInterval(this.data.textTipTimer);
      this.setData({
        inputTextTip: ''
      });
    }
    this.toolPanelChange(e);
  },
  toolPanelChange(e) {
    // 触发展示表情、常用语、语音面板
    let value = e.currentTarget.dataset.value
      ? e.currentTarget.dataset.value
      : '';
    let lastMessageId = this.data.lastMessageId;
    if (value !== '') {
      if (value == 'voice') {
        this.checkRecordVoicePermission();
      }
      let length = 0;
      if (this.data.message && (length = this.data.message.length) > 0) {
        lastMessageId = this.data.message[length - 1].id;
      }
      console.log('change-lastMessageId', lastMessageId);
      this.setData({
        lastMessageId: lastMessageId
      });
    }
    this.setData({
      toolPanelValue: this.data.toolPanelValue === value ? '' : value
    });
  },
  checkRecordVoicePermission() {
    console.log('checkRecordVoicePermission');
    let authPermission = false;
    wx.getSetting({
      success(res) {
        console.log(res.authSetting);
        if (!res.authSetting['scope.record']) {
          //获取录音权限
          wx.authorize({
            scope: 'scope.record',
            success() {
              console.log('授权成功');
            },
            fail() {
              wx.showModal({
                title: '提示',
                content: '尚未进行授权，部分功能将无法使用',
                showCancel: false,
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success: res => {
                        if (!res.authSetting['scope.record']) {
                          wx.authorize({
                            scope: 'scope.record',
                            success() {
                              authPermission = true;
                              console.log('授权成功');
                            },
                            fail() {
                              authPermission = false;
                              console.log('用户点击取消');
                            }
                          });
                        }
                      },
                      fail: function () {
                        authPermission = false;
                        console.log('授权设置录音失败');
                      }
                    });
                  } else if (res.cancel) {
                    authPermission = false;
                    console.log('用户点击取消');
                  }
                }
              });
            }
          });
        }
      }
    });
    return authPermission;
  },
  stopCurrentPlayVoiceMessage() {
    console.log('页面卸载时停止语音播放');
    // 停止正在播放的语音
    let messages = this.data.messages;
    messages &&
      messages
        .filter(item => item.msgType === 'voice')
        .map(item => {
          if (item.voicePlay === true) {
            item.voicePlay = false;
            // 停止语音播放
            // this.data.innerAudioContext.stop();
            this.backgroundAudioManager.stop();
          }
        });
    this.setData({
      messages
    });
  },
  audioTouchStart(e) {
    console.log('touchStart');
    // 检查语音授权
    if (this.checkRecordVoicePermission()) {
      return;
    }
    // 开启长按录制语音屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: true,
      success: () => {
        console.log('长按录制语音播放屏幕常亮');
      }
    });
    // 按住开始说话-开始录音之前如果存在正在播放的语音,停止正在播放的语音
    this.stopCurrentPlayVoiceMessage();
    let point = e.touches[0];
    this.setData({
      showText: '松开发送',
      startPoint: [point.pageX, point.pageY],
      voiceSeconds: 0
    });
    // 重置语音interval
    clearInterval(this.data.voiceSencondsTimer);
    let voiceSeconds = 0;
    let voiceSencondsTimer = setInterval(() => {
      voiceSeconds++;
      let remainingSeconds = this.data.voiceMaxSeconds - voiceSeconds;
      if (remainingSeconds <= 10 && remainingSeconds >= 0) {
        wx.showToast({
          title: '上滑取消发送',
          image: '../../images/number/A' + remainingSeconds + '.png',
          duration: 60000
        });
      }
      this.setData({
        voiceSeconds
      });
    }, 1000);
    this.setData({
      voiceSencondsTimer,
      sendVoiceToast: 1 // 展示正在录制语音提示
    });

    wx.showToast({
      title: '上滑取消发送',
      image: '../../images/voice/record_voice.png',
      duration: 60000
    });
    //开始录音
    this.data.recorderManager.start({
      duration: 60000,
      format: 'aac'
    });
  },
  audioTouchEnd(e) {
    console.log('长按结束录制语音');
    // 长按结束录制语音解除屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: false,
      success: () => {
        console.log('长按结束录制语音解除屏幕常亮');
      }
    });
    this.setData({
      showText: '按住说话'
    });
    wx.hideToast();
    clearInterval(this.data.voiceSencondsTimer);
    // 结束录音
    this.data.recorderManager.stop();
  },
  audioTouchMove(e) {
    // 当前触摸点坐标
    let curPoint = [e.touches[0].pageX, e.touches[0].pageY];
    let startPoint = this.data.startPoint;
    // 判断是上移才做处理
    if (startPoint[1] > curPoint[1]) {
      // 开始触控点往以y为界限向左移动
      let y = startPoint[1] - curPoint[1];
      if (y >= 25) {
        if (this.data.sendVoiceToast === 1) {
          wx.showToast({
            title: '松开取消发送',
            image: '../../images/voice/delete_voice.png',
            duration: 60000
          });
        }

        // 暂停录音
        // this.data.innerAudioContext.pause;
        this.data.recorderManager.pause();
        clearInterval(this.data.voiceSencondsTimer);
        // 标记处于录音删除状态
        this.setData({
          deleteVoice: true,
          sendVoiceToast: 2, // 展示松开取消录音提示
          voiceSencondsTimer: null
        });
      } else {
        if (this.data.sendVoiceToast === 2) {
          wx.showToast({
            title: '上滑取消发送',
            image: '../../images/voice/record_voice.png',
            duration: 60000
          });
          this.setData({
            sendVoiceToast: 1
          });
        }
        // 继续录音
        // this.data.innerAudioContext.resume;
        this.data.recorderManager.resume();
        // 继续计算录音时长
        let voiceSeconds = this.data.voiceSeconds;
        let voiceSencondsTimer = this.data.voiceSencondsTimer;
        if (!voiceSencondsTimer) {
          voiceSencondsTimer = setInterval(() => {
            voiceSeconds++;
            let remainingSeconds = this.data.voiceMaxSeconds - voiceSeconds;
            if (remainingSeconds <= 10 && remainingSeconds >= 0) {
              wx.showToast({
                title: '上滑取消发送',
                image: '../../images/number/A' + remainingSeconds + '.png',
                duration: 60000
              });
            }
            this.setData({
              voiceSeconds
            });
          }, 1000);
        }
        this.setData({
          voiceSencondsTimer,
          deleteVoice: false
        });
      }
    }
  },
  audioPlay(e) {
    console.log('audioPlay 开始播放语音');
    this.backgroundAudioManager.stop();
    let message = e.currentTarget.dataset.message;
    let messages = this.data.messages;
    messages && messages.filter(item => item.msgType === 'voice')
      .forEach(msg => {
        msg.voicePlay = false;
        if (msg.id === message.id) {
          if (msg.read == 0) {
            msg.firstRead = true;
          }
          msg.voicePlay = true;
          msg.read = 1;
        }
      });
    this.commonAudioPlayFun(message);
    this.setData({
      messages
    });
    // 开启语音播放屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: true,
      success: () => {
        console.log('录音播放开启语音播放屏幕常亮');
      }
    });
  },
  audioStop(e) {
    console.log('audioPlay 停止播放语音');
    let message = e.currentTarget.dataset.message;
    let messages = this.data.messages;
    messages &&
      messages
        .filter(item => item.msgType === 'voice')
        .forEach(msg => {
          if (msg.id === message.id) {
            msg.voicePlay = false;
            msg.firstRead = false;
          }
        });
    // 停止语音播放
    //this.data.innerAudioContext.stop();
    this.backgroundAudioManager.stop();
    this.setData({
      messages
    });
    // 解除语音播放屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: false,
      success: () => {
        console.log('手动停止播放录音解除语音播放屏幕常亮');
      }
    });
  },
  emojiChoose(e) {
    let char = e.target.dataset.char;
    this.setData({
      inputContent: this.data.inputContent + char
    });
  },
  deleteMsg(e) {
    //删除消息
    let msg = this.data.actionMessage;
    let index = this.data.messages.findIndex(v => v.id == msg.id);
    let messages = [...this.data.messages];
    messages.splice(index, 1);
    this.setData({
      messages
    });
    this.tunnel.delMsg({
      id: msg.id && msg.id.split('_')[1],
      uuid: msg.uuid,
      userId: this.data.currentUserInfo.id,
      programId: this.data.programId
    });
  },
  withdrawMsg(e) {
    //撤回消息
    let msg = this.data.actionMessage;
    this.tunnel.withdraw({
      id: msg.id && msg.id.split('_')[1],
      uuid: msg.uuid,
      userName: msg.userName,
      programId: this.data.programId
    });
  },
  reEditMessage(e) {
    //重新编辑
    let message = e.currentTarget.dataset.message;
    this.setData({ inputContent: message.content });
  },
  addBlackList(e) {
    //禁言
    let msg = this.data.actionMessage;
    this.tunnel.addBlackList({
      userId: msg.userId
    });
    this.hideToolsTip();
  },
  scrolltolower(e) {
    this.setData({
      scrollPosition: 'lower'
    });
  },
  scroll(e) {
    if (e.detail.deltaY > 20) {
      this.setData({
        scrollPosition: 'middle'
      });
    }
  },
  getMoreMsg(e) {
    console.log('getMoreMsg');
    if (this.data.loadingMore) {
      console.log('正在进行数据查询');
      return;
    }

    let time = new Date().getTime();
    if (this.preTime && time - this.preTime < 2000) {
      console.log('操作太频繁');
      return;
    }

    if (this.data.msgNoMore) {
      let firstMessage = this.data.messages && this.data.messages[0];
      if (firstMessage && firstMessage.content !== '没有更多数据了') {
        this.unshiftMessage(this.createSystemMessage('没有更多数据了'));
      }
      console.log('没有更多消息了');
      return;
    }

    this.setData({
      loadingMore: true
    });
    let pageNum = this.data.msgPageNum;
    setTimeout(() => {
      console.log('显示出加载数据的效果');
      this.getData(newMessage => {
        if (pageNum >= 2) {
          this.setData({
            lastMessageId: newMessage.id
          });
        }
      });
    }, 2000);
    this.preTime = time;
  },
  getData(callbackFun) {
    // 拉去消息记录
    let self = this;
    let pageNum = this.data.msgPageNum;
    let pageSize = this.data.msgPageSize;
    this.setData({
      loadingMore: true
    });
    let param = {
      programId: self.data.programId,
      currentUser: this.data.currentUserInfo.id,
      pageSize,
      pageNum
    };
    if (this.data.noticeMessageId) {
      param.noticeMessageId = this.data.noticeMessageId;
    }
    qcloud.request({
      url: config.service.getPagingMessages,
      data: param,
      success: res => {
        let newMessages = res.data.data.list;
        if (!newMessages || newMessages.length < 1) {
          // 顶部添加一条提示没有更多消息了
          let firstMessage = this.data.messages && this.data.messages[0];
          if (firstMessage && firstMessage.content !== '没有更多数据了') {
            this.unshiftMessage(this.createSystemMessage('没有更多数据了'));
          }
          self.setData({
            loadingMore: false,
            msgNoMore: newMessages.length < pageSize
          });
          if (callbackFun && typeof callbackFun === 'function') {
          console.log('getData方法分页查询消息数据以后,执行回调');
          callbackFun(newDataLastObj);
        }
          return;
        }
        // 调整消息为正确的顺序
        newMessages.reverse();
        let newMessageImages = [];

        newMessages = newMessages.filter(item => {
          // 最新逻辑根据 message.delete = 1 代表当前用于已经删除过改条消息不进行展示
          return item.delete != 1;
        });

        newMessages.forEach(item => {
          this.convertMessage(item);
          // 撤回的图片在预览中不再显示
          if (item.msgType === 'image' && item.status !== '2') {
            newMessageImages.push(item.content);
          }
        });
        let newLength = newMessages.length;
        let messages = newMessages.concat([...self.data.messages]);
        let talkingImageList = newMessageImages.concat([
          ...self.data.images.talkingImageList
        ]);
        self.setData({
          msgNoMore: newMessages.length < pageSize,
          msgPageNum: pageNum + 1,
          messages,
          images: Object.assign({}, this.data.images, { talkingImageList }),
          loadingMore: false
        });

        // 回调函数
        let newDataLastObj = messages[newLength];
        console.log('callbackFun',callbackFun)
        if (callbackFun && typeof callbackFun === 'function') {
          console.log('getData方法分页查询消息数据以后,执行回调');
          callbackFun(newDataLastObj);
        }
      }
    });
  },
  convertMessage(message) {
    // 滚动到指定位置-首字母不能是数字,故给id加上前缀
    message.id = 'history_' + message.id;
    message.photo = message.photo && this.data.fileHost + message.photo;
    message.photo1 = message.photo1 && this.data.fileHost + message.photo1;
    message.photo2 = message.photo2 && this.data.fileHost + message.photo2;
    // 消息状态为撤回状态做处理
    if (message.status === '2') {
      message.withdrawContent = message.userName === this.data.currentUserInfo.name
        ? '你撤回了一条消息' : `"${message.userName}" 撤回了一条消息`;
    }
    message.voicePlay = false;
    if (message.msgType === 'voice' && message.voiceSeconds && message.voiceSeconds !== 'null') {
      let totalWidth = wx.getSystemInfoSync().windowWidth;
      let unit = 2; //
      let startWidth = 46;
      if (totalWidth > 500) {
        unit = 5;
        startWidth = 78;
      }
      message.voiceWidth = startWidth + unit * message.voiceSeconds;
    } else if (message.msgType === 'link') {
      message.content = JSON.parse(message.content);
    } else if (message.msgType === 'image' && message.detail) {
      let totalWidth = wx.getSystemInfoSync().windowWidth;
      let maxWidth = totalWidth * 0.4;
      let maxHeight = totalWidth * 0.4;
      let widthAndHeight = message.detail && JSON.parse(message.detail);
      let width = widthAndHeight.width;
      let height = widthAndHeight.height;
      let overflowWidth = width > maxWidth ? width - maxWidth : 0;
      let overflowHeight = height > maxHeight ? height - maxHeight : 0;
      if (overflowWidth > overflowHeight) {
        // 以宽为标准缩放
        let widthScale = maxWidth / width;
        let realHeight = height * widthScale;
        message.width = `${maxWidth}px`;
        message.height = `${realHeight}px`;
      } else if (overflowWidth < overflowHeight) {
        // 以高为标准缩放
        let heightScale = maxHeight / height;
        let realWidth = width * heightScale;
        message.width = `${realWidth}px`;
        message.height = `${maxWidth}px`;
      } else if (overflowWidth > 0 && overflowHeight > 0 && overflowWidth == overflowHeight) {
        // 宽和高一样
        message.width = `${maxWidth}px`;
        message.height = `${maxHeight}px`;
      } else {
        // 自适应
        message.width = `${width}px`;
        message.height = `${height}px`;
      }
      message.content = this.data.fileHost + message.content;
    }
  },
  subscribeMessage() {
    // 订阅一次消息推送
    var self = this;
    var userInfo = this.data.currentUserInfo;
    var programId = this.data.programId;
    if (this.data.currentUserInfo != 1 && this.data.currentUserInfo.templateId) {
      wx.requestSubscribeMessage({
        tmplIds: [`${this.data.currentUserInfo.templateId}`],
        success (res) {
          wx.request({
            url: `${config.service.updateNoticeSubUrl}?userId=${userInfo.id}&programId=${programId}`,
            method:"GET",
            data:{},
            success (res) {
            }
          })
        },
        fail (res) {
          console.log('订阅一次消息推送-fail', res);
        },
        complete (res) {
          console.log('订阅一次消息推送-complete', res);
        },
      })
    }
  },
  showShareModal() {
    // 底部弹出框-展示分享框遮罩层
    var self = this;
    self.setData({
      hideShareModal: false
    });
    var animation = wx.createAnimation({
      duration: 600, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease' //动画的效果 默认值是linear
    });
    this.animation = animation;
    setTimeout(function () {
      self.fadeIn(); //调用显示动画
    }, 200);
  },
  hideShareModal: function () {
    // 底部弹出框-隐藏分享框遮罩层
    var that = this;
    var animation = wx.createAnimation({
      duration: 800, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease' //动画的效果 默认值是linear
    });
    this.animation = animation;
    that.fadeDown(); //调用隐藏动画
    setTimeout(function () {
      that.setData({
        hideShareModal: true
      });
    }, 720); //先执行下滑动画，再隐藏模块
  },
  // 底部弹出框-显示遮罩层
  showModal: function (e) {
    // 默认底部提示: 安卓操作系统是没有底部提示的
    let isShowModal = false;
    if (this.data.platform == 'ios') {
      isShowModal = true;
    }
    this.hideToolsTip();
    let bottomDialogTipText = e.currentTarget.dataset.value;
    if (bottomDialogTipText === '删除') {
      isShowModal = true;
    }
    if (isShowModal) {
      // 显示提示框-ios操作系统
      var self = this;
      self.setData({
        hideModal: false,
        bottomDialogTipText
      });
      var animation = wx.createAnimation({
        duration: 600, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
        timingFunction: 'ease' //动画的效果 默认值是linear
      });
      this.animation = animation;
      setTimeout(function () {
        self.fadeIn(); //调用显示动画
      }, 200);
    } else {
      // 不显示提示框-安卓操作系统
      if (bottomDialogTipText === '撤回') {
        this.withdrawMsg();
      }
    }
  },
  comfirmModal: function () {
    let text = this.data.bottomDialogTipText;
    if (text === '删除') {
      this.deleteMsg();
    } else if (text === '撤回') {
      this.withdrawMsg();
    }
    this.hideModal();
  },
  // 底部弹出框-隐藏遮罩层
  hideModal: function () {
    var that = this;
    var animation = wx.createAnimation({
      duration: 800, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease' //动画的效果 默认值是linear
    });
    this.animation = animation;
    that.fadeDown(); //调用隐藏动画
    setTimeout(function () {
      that.setData({
        hideModal: true
      });
    }, 720); //先执行下滑动画，再隐藏模块
  },
  // 底部弹出框-动画集
  fadeIn: function () {
    this.animation.translateY(0).step();
    this.setData({
      animationData: this.animation.export() //动画实例的export方法导出动画数据传递给组件的animation属性
    });
  },
  fadeDown: function () {
    this.animation.translateY(300).step();
    this.setData({
      animationData: this.animation.export()
    });
  }
});
